package com.server.http.handler.impl;

import java.util.List;

import com.server.background.data.RankData;
import com.server.conditionenum.HttpReturnStatus;
import com.server.http.handler.HttpHandler;
import com.server.http.request.HttpRequestMessage;
import com.server.http.response.HttpResponseMessage;
import com.server.mine.net.HttpProtocol;
import com.server.tools.AppData;
import com.server.tools.EmojiUtils;

/**
* @author	李小布
* @email	397554852@qq.com
* @version	创建时间：2018年10月8日 上午10:22:35
*/
public class PutRankData extends HttpHandler{
	@Override
	public void handle(HttpRequestMessage request, HttpResponseMessage response) {
		int failMsg = 0;
		String rkname = request.getParameter("rkname");
		String uname = request.getParameter("uname");
		String uhead = request.getParameter("uhead");
		String info = request.getParameter("info");
		int index = 0;
		long uid = 0;
		int value = 0;
		if(uhead == null)uhead = "";
		if(uid < 0 || rkname == null || "".equals(rkname) || "null".equals(rkname) || "null".equals(uname) || uname == null || "".equals(uname)) {
			failMsg = -1;
		}else {
			try {
				uid = Long.parseLong(request.getParameter("uid"));
				value = Integer.parseInt(request.getParameter("value"));
				uname = EmojiUtils.emoji2Unicode(uname);
				List<RankData> rank = AppData.ClientGetRankList(rkname);
				index = rank.size();
				if(index == 0) {
					RankData rd = new RankData();
					rd.uid = uid;
					rd.name = uname;
					rd.head = uhead;
					rd.value = value;
					rd.info = info;
					rank.add(rd);
				}else {
					for(int i = 0; i < rank.size(); i++) {
						if(rank.get(i).uid == uid) {
							rank.remove(i);
							index = rank.size();
							break;
						}
					}
					int self_index = -1;
					for(int i = index - 1; i >= 0; i--) {
						if(value > rank.get(i).value) index = i;
						if(uid == rank.get(i).uid) self_index = i;
					}
					
					if(index < 50) {
						RankData rd = new RankData();
						rd.uid = uid;
						rd.name = uname;
						rd.head = uhead;
						rd.value = value;
						rd.info = info;
						if(self_index > -1) {
							if(index == self_index) {
								rank.set(index, rd);
							}else if(index > self_index) {
								rank.add(index, rd);
								rank.remove(self_index);
							}else if(index < self_index) {
								rank.remove(self_index);
								rank.add(index, rd);
							}
						}else {
							rank.add(index, rd);
						}
					}
					
					if(rank.size() > 50) {
						rank.remove(50);
					}
				}
			} catch (Exception e) {
				failMsg = -1;
			}
			
		}
		if(failMsg == 0) {
			SetReturnData(response,index,HttpProtocol.PUTRANKDATA,HttpReturnStatus.Successed);
		}else {
			SetReturnData(response,failMsg,HttpProtocol.PUTRANKDATA,HttpReturnStatus.Failed);
		}
	}
}